import React, { useState, useMemo } from 'react';
import { Avatar, Button, Comment, Form, Input, Spin } from 'antd';
import { useTranslation } from 'react-i18next';

import ExampleComment from '../ExampleComment';
import { submitCommentApi } from '@src/services/company';

const { TextArea } = Input;

const defaultProfile = '/img/placeholder.jpg';

const Editor = ({ onChange, onSubmit, submitting, value, t }) => (
  <>
    <Form.Item>
      <TextArea rows={4} onChange={onChange} value={value} />
    </Form.Item>
    <Form.Item>
      <Button htmlType="submit" loading={submitting} onClick={onSubmit} type="primary">
        {t('Comment')}
      </Button>
    </Form.Item>
  </>
);

const CommentListCom = ({
  companyInfo,
  commentsData,
  getCommentLoading,
  onRefresh
}) => {
  const { t }  = useTranslation();

  const [submitting, setSubmitting] = useState(false);
  const [commentValue, setCommentValue] = useState('');

  const handleSubmit = async () => {
    if (!commentValue) return;
    setSubmitting(true);

    const res = await submitCommentApi({
      business_server_id: companyInfo.business_server_id,
      content: commentValue,
      // parent_id
    });

    setSubmitting(false);

    if (!res) return;

    setCommentValue('');
    onRefresh();
  };

  const handleCommentChange = (e) => {
    setCommentValue(e.target.value);
  };

  const commentFunc = (data) => {
    return data.map(item => {
      return (
        <ExampleComment key={item.comment_id} data={item} onRefresh={onRefresh}>
          {
            (item.child_comments?.length > 0) && commentFunc(item.child_comments)
          }
        </ExampleComment>
      )
    })
  }

  const CommentListMap = useMemo(() => {
    return commentFunc(commentsData)
  }, [commentsData])

  return (
    <Spin spinning={getCommentLoading}>
      {CommentListMap}
      <Comment
        avatar={<Avatar src={defaultProfile} alt="" />}
        content={
          <Editor
            onChange={handleCommentChange}
            onSubmit={handleSubmit}
            submitting={submitting}
            value={commentValue}
            t={t}
          />
        }
      />
    </Spin>
  )
};

export default CommentListCom;